package com.colter.project.util.numric;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NumricUtil {
	public static void main(String[] args) {
		StartAndEnd[] noes = new StartAndEnd[5];
		noes[0] = new StartAndEnd(1, 5);
		noes[1] = new StartAndEnd(6, 8);
		noes[2] = new StartAndEnd(10, 12);
		noes[3] = new StartAndEnd(20, 15);
		noes[4] = new StartAndEnd(40, 17);
		System.out.println(mergeToSection(noes));
	}

	/**
	 * A object has a start and a end no. The mean a section of numbers. Then
	 * merge the continuous.
	 * 
	 * @param noes
	 * @return
	 */
	public static List<StartAndEnd> mergeToSection(StartAndEnd[] noes) {
		Arrays.sort(noes);
		List<StartAndEnd> list = new ArrayList<>();

		StartAndEnd se = new StartAndEnd();
		boolean start = true;
		for (int i = 0; i < noes.length; i++) {
			StartAndEnd temp = noes[i];
			if (start) {
				se.setStartNo(temp.getStartNo());
				se.setEndNo(temp.getEndNo());
				start = false;
			} else {
				if (Math.abs(temp.getStartNo() - se.getEndNo()) <= 1 || temp.getStartNo() < se.getEndNo()) {
					if (se.getEndNo() < temp.getEndNo()) {
						se.setEndNo(temp.getEndNo());
					} else {
						se.setEndNo(se.getEndNo());
					}
				} else {
					list.add(se);
					se = new StartAndEnd();
					se.setStartNo(temp.getStartNo());
					se.setEndNo(temp.getEndNo());
				}
			}

		}

		list.add(se);

		return list;
	}
}

class StartAndEnd implements Comparable<StartAndEnd> {
	private int startNo;
	private int endNo;

	@Override
	public String toString() {
		return "StartAndEnd [startNo=" + startNo + ", endNo=" + endNo + "]";
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public void swap() {
		int temp = this.getStartNo();
		this.setStartNo(this.getEndNo());
		this.setEndNo(temp);
	}

	@Override
	public int compareTo(StartAndEnd o) {
		if (this.startNo > this.endNo) {
			this.swap();
		}

		if (o.startNo > o.endNo) {
			o.swap();
		}

		if (this.startNo < o.startNo) {
			return -1;
		} else if (this.startNo > o.startNo) {
			return 1;
		}

		if (this.endNo < o.endNo) {
			return -1;
		} else if (this.endNo > o.endNo) {
			return 1;
		}

		return 0;
	}

	public StartAndEnd(int startNo, int endNo) {
		super();
		this.startNo = startNo;
		this.endNo = endNo;
	}

	public StartAndEnd() {
		super();
	}

}